package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"
)

//CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app redis_clean.go

var (
	pool *redis.Pool
)

func init() {
	//pool = newPool(":6379", "", 0)
	pool = newPool("127.0.0.1:6379", "", 0)
	cleanupHook()
}

func cleanupHook() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	signal.Notify(c, syscall.SIGKILL)
	go func() {
		<-c
		pool.Close()
		os.Exit(0)
	}()
}

func newPool(addr, password string, db int) *redis.Pool {
	return &redis.Pool{
		MaxActive:   100, // Pool max size: 100
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		// Dial or DialContext must be set. When both are set, DialContext takes precedence over Dial.
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", addr)
			if err != nil {
				return nil, err
			}
			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}
			if _, err := c.Do("SELECT", db); err != nil {
				c.Close()
				return nil, err
			}
			return c, nil
		},
		// Other pool configuration not shown in this example.
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
	}
}

// SCAN 查询全部 Key
func GetKeys() ([]string, error) {
	conn := pool.Get()
	defer conn.Close()

	prefix := "m::message_"
	pattern := prefix + "*"

	iter := 0
	var keys []string
	for {
		// SCAN [cursor] MATCH [pattern]
		arr, err := redis.Values(conn.Do("SCAN", iter, "MATCH", pattern))
		if err != nil {
			return keys, fmt.Errorf("error retrieving '%s' keys", pattern)
		}

		iter, _ = redis.Int(arr[0], nil)
		k, _ := redis.Strings(arr[1], nil)
		//keys = append(keys, k...)

		// 筛选出 永远不会过期
		conn.Send("MULTI")
		for _, v := range k {
			conn.Send("TTL", v)
		}
		res, err := redis.Ints(conn.Do("EXEC"))

		month6, err := time.Parse("2006-01-02", "2021-06-01")
		if err != nil {
			return keys, err
		}
		monthDiff := time.Now().Unix() - month6.Unix()
		for index, value := range k {
			// -2 不存在 -1 永远不会过期
			if res[index] == -1 {
				keys = append(keys, value)
				// println(value)
				// go run redis_clean.go | awk '{print $1}'
				// go run redis_clean.go 2>&1
				// go run redis_clean.go | awk '{print $1}' 2>&1 | tee out.txt
				// os.Stdout.WriteString(value+"\n")
				if strings.HasPrefix(value, prefix) {
					dateStr := strings.Replace(value, prefix, "", -1)[0:10]
					if timeObj, err := time.Parse("2006-01-02", dateStr); err == nil {
						//os.Stdout.WriteString(value+"\n")
						//fmt.Println(time.Now().Unix() - timeObj.Unix(),monthDiff, dateStr)
						if time.Now().Unix()-timeObj.Unix() > monthDiff {
							conn.Do("DEL", value)
							os.Stdout.WriteString("del: " + value + "\n")
						}
					}
				}
			}
		}

		if iter == 0 {
			break
		}
	}

	return keys, nil
}
func main() {
	if keys, err := GetKeys(); err != nil {
		panic(err)
	} else {
		for _, v := range keys {
			fmt.Println(v)
		}
	}
}
